<!--公告管理页-->
<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">公告信息</span>
    <el-button @click="dialogVisible=true" type="primary"
               style="float:right;margin-top:13px;">新建公告</el-button>
  </div>
  <!-- 新建公告 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible"
             style="width:1000px;padding:40px;" :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="公告类型">
            <el-input placeholder="请输入内容" v-model="saveNoticeForm.type"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公告标题">
            <el-input placeholder="请输入内容" v-model="saveNoticeForm.title"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="公告提交人">
            <el-input placeholder="请输入内容"  readonly :value="user.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公告状态">
            <el-radio-group v-model="saveNoticeForm.state">
              <el-radio border label="审核中" value= "1" style="margin:0;"></el-radio>
              <el-radio border label="已审核" value= "2"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="公告上传">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisibleClose">
              <img w-full :src="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveNotice">确定</el-button>
    </template>
  </el-dialog>
  <!-- 车辆搜索卡片 -->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="公告标题">
        <el-input placeholder="请输入公告标题" style="width:220px;"
                  v-model="searchNoticeForm.title" @keydown.enter="loadNotice"></el-input>
      </el-form-item>
      <el-form-item label="公告状态" style="width:290px;">
        <el-select placeholder="请选择公告状态"
                  v-model="searchNoticeForm.state" @change="loadNotice">
          <el-option label="审核中" value="1"></el-option>
          <el-option label="已审核" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="公告提交人" style="width:290px;">
        <el-input placeholder="请输入公告提交人" style="width:220px;"
                  v-model="searchNoticeForm.username" @keydown.enter="loadNotice"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadNotice">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 公告列表 -->
  <el-card style="margin:20px;">
    <el-table :data="noticeArr">
      <el-table-column type="index" label="公告编号" width="80" align="center"/>
      <el-table-column prop="type" label="公告类型" align="center"/>
      <el-table-column prop="title" label="公告标题" align="center"/>
      <el-table-column prop="username" label="公告提交人" align="center"/>
      <el-table-column prop="createTime" label="创建时间" align="center"/>
      <el-table-column prop="updateTime" label="更新时间" align="center"/>
      <el-table-column prop="noticeAuditor" label="公告审核人" align="center"/>
      <el-table-column prop="state" label="公告状态" align="center"
                       :formatter="noticeStatusFormatter"/>
      <el-table-column prop="state" label="修改公告状态" align="center">
        <template #default="scope">
          <!--  scope.row就代表表格中当前行的用户对象,也就是后端返回的propertyVO -->
          <el-switch active-value="2" inactive-value="1"
                     v-model="scope.row.state"
                     @change="changeState(scope.row.id,scope.row.state,scope.row.username)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <a :href="scope.row.noticePath">点我查看公告详情</a>
          <hr>
          <el-button link type="primary" size="small" @click="editNotice(scope.row.id)">编辑</el-button>
          <el-button link type="primary" size="small" @click="deleteNotice(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
<script setup>
import {onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {createRouter as value} from "vue-router";

const tempFilePath = ref('');
//获取当前登录的用户信息
const user = ref(getUser());

const handleExceed = (files, fileList) => {
  ElMessage.warning(`当前限制最多上传 1 个图片。本次选择了 ${files.length} 个图片，共选择了 ${files.length + fileList.length} 个图片`);
};
/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisibleClose = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);

  // 尝试从 uploadFile.response.data 获取图片路径
  let imgUrl = uploadFile.response?.data;

  // 如果没有从 response 中获取到图片路径，则从 fileList 中获取
  if (!imgUrl) {
    // 假设 fileList 中的每个文件对象都有一个 url 属性，表示图片路径
    const fileInList = fileList.value.find(file => file.uid === uploadFile.uid);
    if (fileInList && fileInList.url) {
      imgUrl = fileInList.url;
    } else {
      ElMessage.error('无法获取图片路径!');
      return;
    }
  }

  // 发送删除请求
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功!');
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(() => {
        ElMessage.error('删除失败!');
      });
};
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisibleClose.value = true;
  console.log(uploadFile);
  //console.log(fileList.value[0].response.data);
}
/**图片上传相关代码结束**/
//控制新增公告弹窗是否显示
const dialogVisible = ref(false);
//定义变量控制dialog的标题
const dialogTitle = ref('新增公告');
//定义数组用来保存车辆类型字典项
const noticeTypeArr = ref([]);
const batteryTypeArr = ref([]);
// onMounted(()=>{
//   loadDictOptions(vehicleTypeArr,'vehicle_type');
//   loadDictOptions(batteryTypeArr,'battery_type');
// })

//定义对象用来保存公告的搜索条件
const searchNoticeForm = ref({username:'',type:'',state:''});
//定义数组对象用来保存公告列表的数据
const noticeArr = ref([]);
//定义加载公告的方法
const loadNotice= ()=>{
  let data = qs.stringify(searchNoticeForm.value);
  axios.get(BASE_URL+'/v1/property/notice/select?'+data).then((response)=>{
    if(response.data.code==2000){
      console.log('Loaded notice:', response.data.data); // 添加日志输出
      noticeArr.value = response.data.data.map(item => ({
        ...item,
        state: item.state ? item.state.toString() : '1', // 确保 state 为 '1' 或 '2'
        noticePath: 'http://localhost:8080' + item.noticePath // 设置每个公告的详情链接
      }));
      // 打印 noticePath 的值
      noticeArr.value.forEach(notice => {
        console.log('noticePath:', notice.noticePath);
      });
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

//定义修改合同状态的方法
const changeState = (id,state,username)=>{
  noticeArr.value.noticeAuditor = username;
  noticeArr.value.id = id;
  noticeArr.value.state = state;
  let data = qs.stringify(noticeArr.value);
  axios.post(BASE_URL+'/v1/property/notice/update?'+data)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('修改状态成功!');
          loadNotice();
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
//定义重置搜索的方法
const resetSearch= ()=>{
  searchNoticeForm.value = {};
  loadNotice();
}
//一进到页面立即执行调用加载公告的方法
 onMounted(()=>{
   loadNotice();
 })

//对表格中公告状态显示的文字进行转换
const noticeStatusFormatter = (row, column,cellValue,index)=>{
  if(cellValue == 1){
    cellValue = '审核中';
  }else if(cellValue == 2){
    cellValue = '已审核';
  }
  return cellValue;
}
//对公告类型显示内容进行文字转换
const noticeTypeFormatter = (row,column,cellValue,index)=>{
  //如果字典项数组没有值,直接返回当前单元格的值,比如 10
  if(!noticeTypeArr.value){
    return cellValue;
  }
  //依次遍历出字典项数组中的每个字典项
  for(let item of noticeTypeArr.value){
    //如果字典项的value值与当前单元格的值一致
    if(item.value == cellValue){
      //就把当前单元格的值改为此字典项的label值,比如 轿车
      cellValue = item.label;
    }
  }
  // if(cellValue == 10){
  //   cellValue = '轿车';
  // }else if(cellValue == 20){
  //   cellValue = '货车';
  // }else if(cellValue == 30){
  //   cellValue = '客车';
  // }else if(cellValue == 40){
  //   cellValue = '挂车';
  // }
  return cellValue;
}
//对电池类型显示内容进行文字转换
const batteryTypeFormatter = (row,column,cellValue,index)=>{
   if(!batteryTypeArr.value){
    return cellValue;
  }
  for(let item of batteryTypeArr.value){
    if(item.value == cellValue){
      cellValue = item.label;
    }
  }
  // if(cellValue == 10){
  //   cellValue = '铅酸蓄电池';
  // }else if(cellValue == 20){
  //   cellValue = '镍氢电池';
  // }else if(cellValue == 30){
  //   cellValue = '钠硫电池';
  // }else if(cellValue == 40){
  //   cellValue = '二次锂电池';
  // }else if(cellValue == 50){
  //   cellValue = '空气电池';
  // }else if(cellValue == 60){
  //   cellValue = '三元锂电池';
  // }else if(cellValue == 70){
  //   cellValue = '碱性燃料电池';
  // }
  return cellValue;
}
//定义对象用来保存新增车辆弹窗表单的所有数据
const saveNoticeForm = ref({
  type:'',
  title:'',
  state:'',
  noticePath:'',
  username:'',
});
//定义保存公告的方法
const saveNotice = () => {
  saveNoticeForm.value.username = user.value.username;
  // 对数据进行校验
  if (!saveNoticeForm.value.type || saveNoticeForm.value.type.trim() === '') {
    ElMessage.error('请输入公告类型!');
    return;
  }
  if (!saveNoticeForm.value.title || saveNoticeForm.value.title.trim() === '') {
    ElMessage.error('请输入公告标题!');
    return;
  }
  if (!saveNoticeForm.value.username || saveNoticeForm.value.username.trim() === '') {
    ElMessage.error('请输入公告提交人!');
    return;
  }
  if (!saveNoticeForm.value.state || saveNoticeForm.value.state.trim() === '') {
    ElMessage.error('请选择公告状态!');
    return;
  }


  // 处理公告图片上传
  if(fileList.value.length==0){
    ElMessage.error('请上传公告文件图片!');
    return;
  }
  //
  // 检查 fileList 是否为空
  if (!saveNoticeForm.value.noticePath || saveNoticeForm.value.noticePath.length === 0) {
    // 字符串未定义或为空
    saveNoticeForm.value.noticePath = fileList.value[0].response.data;
  } else {
    console.log(saveNoticeForm.value);
    let data = qs.stringify(saveNoticeForm.value);
    axios.post(BASE_URL + '/v1/property/notice/save', data).then((response) => {
      if (response.data.code == 2000) {
        ElMessage.success('保存成功!');
        // 保存成功后: 关弹窗 + 清除表单数据 + 重新加载所有公告数据
        dialogVisible.value = false;
        saveNoticeForm.value = {};
        fileList.value = [];//清空图片上传组件的数据
        loadNotice();
      } else {
        ElMessage.error('保存失败!');
      }
    }).catch((error) => {
      ElMessage.error('请求出错!');
    });
  }
}
//定义关闭保存公告弹窗的方法
const handleClose = ()=>{
  if(confirm('您确认要关闭本弹窗吗?')){
    dialogVisible.value = false;//关闭弹窗
    saveNoticeForm.value = {};//清空表单数据
    fileList.value = [];
  }
}

//定义编辑公告的方法 出弹窗+改标题+回显数据
const editNotice = (id)=>{
  dialogVisible.value = true;
  dialogTitle.value = '编辑公告';
  //根据当前车辆id回显弹窗表单中此车辆的详细数据
  axios.get(BASE_URL+'/v1/property/notice/select?id='+id).then((response)=>{
    if (saveNoticeForm.value.noticePath) {
      fileList.value.push({url:BASE_URL + saveNoticeForm.value.noticePath})
    }
    if(response.data.code==2000){
      saveNoticeForm.value = response.data.data[0];
      user.value.username = response.data.data[0].username;
      // 确保 state 是字符串类型
      saveNoticeForm.value.state = saveNoticeForm.value.state.toString();
      // 设置图片列表
      if (saveNoticeForm.value.noticePath) {
        fileList.value = [{ url: BASE_URL +saveNoticeForm.value.noticePath }];
      }

    }else{
      ElMessage.error(response.data.msg);
    }
  });
}
//定义删除公告的方法
const deleteNotice = (noticeId)=>{
  if(confirm('您确认要删除该公告吗?')){
    axios.post(BASE_URL+'/v1/property/notice/delete/'+noticeId).then((response)=>{
      if(response.data.code==2000){
        ElMessage.success('删除成功!');
        //删除成功后,需要重新加载所有的车辆数据列表!
        loadNotice();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}
</script>